/**
 * 
 */
package com.itinsys.enma.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.type.Type;

import net.sf.ehcache.ObjectExistsException;

import com.itinsys.enma.dao.DBTemplate;
import com.itinsys.enma.dao.RoleDAO;
import com.itinsys.enma.dao.hibernate.DBObject;
import com.itinsys.enma.domain.Role;

/**
 * @author pferraz
 *
 */
public class RoleDAOImpl implements RoleDAO {
	
	private static Logger logger=Logger.getLogger("dao");
	
	
	@SuppressWarnings("unchecked")
	public Role getById(int roleId) throws ObjectExistsException {
		List<Role> result=null;
		Session sess=null;
		try{
			sess=DBTemplate.getConnTemplate().getSessionFactory().openSession();
			Query q=sess.createQuery("from r in class com.itinsys.enma.domain.Role where r.id=?");
			q.setParameters(new Object[]{roleId}, new Type[]{Hibernate.INTEGER});
			result=q.list();
			if(result.isEmpty()){
				throw new ObjectExistsException("El rol ingresado no existe");	
			}
		}catch(HibernateException e){
			logger.error("Error al buscar rol por identificador. " ,e);
		}finally {
            if (sess != null){
            	sess.close();	
            }
        }
		return result.get(0);
	}


	@Override
	public void addRole(Role role) {
		DBObject.addObject(role);		
	}

}
